package com.glela.controller;

import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayEbppPdeductPayResponse;
import com.alipay.api.response.AlipayOpenAuthTokenAppQueryResponse;
import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.glela.api.model.AlipayAppKeyInfo;
import com.glela.api.model.AlipayTradeFastpayRefundQueryResponseVo;
import com.glela.api.model.AlipayTradeQueryResponseVo;
import com.glela.api.pay.alipay.component.Alipay;
import com.glela.api.pay.alipay.vo.AlipayRequest;
import com.glela.common.util.JsonUtil;
import com.glela.common.util.NetworkUtil;
import com.glela.order.mapper.OrderObjectMapper;
import com.glela.order.mapper.OrderPayMapper;
import com.glela.order.mapper.OrderSettlementCommisionMapper;
import com.glela.order.model.AfterSales;
import com.glela.order.model.OrderObject;
import com.glela.order.model.OrderPay;
import com.glela.order.model.OrderSettlementCommision;
import com.glela.order.service.AfterSalesService;
import com.glela.order.service.OrderPayService;
import com.glela.order.service.OrderService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.User;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;
import com.glela.statistics.service.UserEarningsService;
import com.glela.talent.model.OrderVip;
import com.glela.talent.service.TalentService;

/**
 *@author liujie
 *@2016年11月3日
 */
@Controller
@RequestMapping("alipay")
public class AlipayController {

	private static Logger logger = LoggerFactory.getLogger(AlipayController.class);
	
	@Autowired
	private Alipay alipay;
	@Resource(name = "orderService2")
	private OrderService orderService2;
	@Autowired
	private AfterSalesService afterSalesService;
	@Autowired
	private TalentService talentService;
	@Autowired
	private OrderSettlementCommisionMapper orderSettlementCommisionMapper;
	@Autowired
	private UserService userService;
	@Autowired
	private OrderPayMapper orderPayMapper;
	@Autowired
	private OrderObjectMapper orderObjectMapper;
	@Autowired
	private UserEarningsService userEarningsService;
	
	@RequestMapping(value = "/getOpenAuthToken", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getOpenAuthToken(@RequestBody AlipayRequest alipayRequest) {
		try {
			if ((alipayRequest.getCode()==null||alipayRequest.getCode().isEmpty())
					&&(alipayRequest.getRefreshToken()==null||alipayRequest.getRefreshToken().isEmpty()))
			{
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			AlipayAppKeyInfo alipayAppKeyInfo=getOrderService().getAlipayAppKeyInfo();
			AlipayOpenAuthTokenAppResponse vo =alipay.getOpenAuthToken(alipayAppKeyInfo, alipayRequest.getCode(), alipayRequest.getRefreshToken()) ;
			if (vo == null ) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29911), HttpStatus.OK);
			}else {
				return new ResponseEntity<>(new ResponseResultModel<>(vo), HttpStatus.OK);
			}
		} catch (AlipayApiException e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	@RequestMapping(value = "/queryOpenAuthToken", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> queryOpenAuthToken(@RequestBody AlipayRequest alipayRequest) {
		try {
			if (ParameterUtils.validParams(alipayRequest.getAppAuthToken()))
			{
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			AlipayAppKeyInfo alipayAppKeyInfo=getOrderService().getAlipayAppKeyInfo();
			AlipayOpenAuthTokenAppQueryResponse vo =alipay.queryOpenAuthToken(alipayAppKeyInfo, alipayRequest.getAppAuthToken());
			if (vo == null ) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29911), HttpStatus.OK);
			}else {
				return new ResponseEntity<>(new ResponseResultModel<>(vo), HttpStatus.OK);
			}
		} catch (AlipayApiException e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * <dl>
	 * <dt>支付宝支付-直连支付宝</dt>
	 * </dl>
	 * @param alipayRequest
	 * @param request
	 * @return ResponseEntity<?>
	 * @author zls
	 * @date 2017年12月4日 下午1:27:25
	 */
	@RequestMapping(value = "/getOrderString", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getOrderString(@RequestBody AlipayRequest alipayRequest, HttpServletRequest request) {
		try {
			if (ParameterUtils.validParams(alipayRequest.getOrderSn())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}

			OrderObject orderObject = getOrderService().selectOrderObjectByOrderSn(alipayRequest.getOrderSn());
			if (orderObject == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20802), HttpStatus.OK);
			}
			if(orderObject.getOpenStore() != null && orderObject.getOpenStore() == 1){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20418), HttpStatus.OK);
			}
			logger.error("用户发起微信支付, 父订单号: {} , 开店单标识: {}", orderObject.getOrderSn(), orderObject.getOpenStore());
			String ipAddress = NetworkUtil.getRealIp(request);
			Map<String, String> orderStringMap = orderPayService.saveAlipay(orderObject.getOrderSn(), ipAddress, orderObject.getTotalFee());
			
			//			AlipayAppKeyInfo alipayAppKeyInfo = getOrderService().getAlipayAppKeyInfo();
			//			Map<String, String> orderStringMap = alipay.getOrderString(alipayAppKeyInfo, alipayRequest.getOrderSn(), orderObject.getTotalFee());
			return new ResponseEntity<>(new ResponseResultModel<>(orderStringMap), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("支付宝直连异常：{}", e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@Autowired
	private OrderPayService orderPayService;
	/**
	 * MaoZeYao
	 * 支付宝购买会员
	 * @param alipayRequest
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getOrderVipString", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getOrderVipString(@RequestBody AlipayRequest alipayRequest,HttpServletRequest request) {
		try {
			if (ParameterUtils.validParams(alipayRequest.getUserId()))
			{
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			/*gwq  验证用户是否可以购买会员*/
			User user=userService.getUser(alipayRequest.getUserId());
			if(user==null){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK);
			}
			if(user.getRoleId()>2){//已经是会员以上级别的了，不需要购买会员
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20275), HttpStatus.OK);
			}
			/*gwq 验证用户是否可以购买会员 结束*/
			OrderVip orderVip = talentService.createOrderVip(alipayRequest.getUserId(), 2);
			if (orderVip==null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20802), HttpStatus.OK);
			}
			AlipayAppKeyInfo alipayAppKeyInfo=getOrderService().getAlipayAppKeyInfo();
			Map<String,String> orderStringMap = alipay.getOrderVipString(alipayAppKeyInfo, orderVip.getOrderSn(), orderVip.getTotalFee());
			return new ResponseEntity<>(new ResponseResultModel<>(orderStringMap), HttpStatus.OK);
		}  catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	@RequestMapping(value = "/aliTradePay", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> aliTradePay(@RequestBody AlipayRequest alipayRequest,HttpServletRequest request) {
		try {
			if (ParameterUtils.validParams(alipayRequest.getCode(),alipayRequest.getOrderSn()))
			{
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			
			OrderObject orderObject=getOrderService().selectOrderObjectByOrderSn(alipayRequest.getOrderSn());
			if (orderObject==null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20802), HttpStatus.OK);
			}
			AlipayAppKeyInfo alipayAppKeyInfo=getOrderService().getAlipayAppKeyInfo();
			AlipayTradePayResponse vo = alipay.aliTradePay(alipayAppKeyInfo, alipayRequest.getCode()
					, alipayRequest.getOrderSn(), orderObject.getTotalFee());
			return new ResponseEntity<>(new ResponseResultModel<>(vo), HttpStatus.OK);
		} catch (AlipayApiException e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		}  catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	@RequestMapping(value = "/alipayEbppPdeductPay", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> alipayEbppPdeductPay(@RequestBody AlipayRequest alipayRequest,HttpServletRequest request) {
		try {
			if (ParameterUtils.validParams(alipayRequest.getOrderSn()))
			{
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			AlipayAppKeyInfo alipayAppKeyInfo=getOrderService().getAlipayAppKeyInfo();
			AlipayEbppPdeductPayResponse vo = alipay.alipayEbppPdeductPay(alipayAppKeyInfo, "", "", ""
					, "", 100, 100);
			return new ResponseEntity<>(new ResponseResultModel<>(vo), HttpStatus.OK);
		} catch (AlipayApiException e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		}  catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * MaoZeYao
	 * 支付宝退款
	 * @param alipayRequest
	 * @param request
	 * @return
	 */
	/*@RequestMapping(value = "/aliRefund", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> aliRefund(@RequestBody AlipayRequest alipayRequest,HttpServletRequest request) {
		try {
			if (ParameterUtils.validParams(alipayRequest.getCustomerServiceNumber())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			// 获取售后信息
			AfterSales afterSale = getOrderService().selectAfterSalesByCustomerServiceNumber(alipayRequest.getCustomerServiceNumber());
			// 获取子订单的信息
			if(afterSale == null){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20802), HttpStatus.OK);
			}
			AlipayAppKeyInfo alipayAppKeyInfo=getOrderService().getAlipayAppKeyInfo();
			OrderInfo orderInfo = getOrderService().selectOrderInfoByOrderInfoSn(afterSale.getOrderInfoSn());
			AlipayTradeRefundResponse response = alipay.alipayRefund(alipayAppKeyInfo, orderInfo.getOrderSn(),
					orderInfo.getPay_id(), afterSale.getRefundMoney(), afterSale.getCustomerServiceNumber());
			if (response.isSuccess()) {
				afterSalesService.userRefundSuccess(afterSale);
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			//return new ResponseEntity<>(new ResponseResultModel<>(vo), HttpStatus.OK);
		} catch (AlipayApiException e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		}  catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}*/
	
	/********************************************
	 * 
	 * <dl>
	 * <dt>支付宝订单查询接口</dt>
	 * </dl>
	 * 
	 * @return ResponseEntity<?>
	 * @author gwq
	 * @date 2017年12月12日 13:44:05
	 * 
	 ********************************************/
	@RequestMapping(value = "/alipayTradeQuery", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> alipayTradeQuery(@RequestBody AlipayRequest alipayRequest,HttpServletRequest request){
		try {
			String paySn=alipayRequest.getPaySn();
			if (ParameterUtils.validParams(paySn)){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			//查询订单
			AlipayAppKeyInfo alipayAppKeyInfo=orderService2.getAlipayAppKeyInfo();
			AlipayTradeQueryResponse responese=alipay.alipayTradeQuery(alipayAppKeyInfo,paySn);
			if(responese.isSuccess()){//请求成功
				return new ResponseEntity<>(new ResponseResultModel<>(new AlipayTradeQueryResponseVo(responese)), HttpStatus.OK);
			}else{
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		} 
	}
	
	/********************************************
	 * 
	 * <dl>
	 * <dt>统一收单交易退款查询</dt>
	 * </dl>
	 * 
	 * @return ResponseEntity<?>
	 * @author gwq
	 * @date 2017年12月12日 13:44:05
	 * 
	 ********************************************/
	@RequestMapping(value = "/alipayTradeFastpayRefundQuery", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> alipayTradeFastpayRefundQuery(@RequestBody AlipayRequest alipayRequest,HttpServletRequest request){
		try {
			String paySn=null;String customerServiceNumber=null;
			paySn=alipayRequest.getPaySn();
			customerServiceNumber=alipayRequest.getAfterSn();
			if (ParameterUtils.validParams(paySn,customerServiceNumber)){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			//查询订单
			AlipayAppKeyInfo alipayAppKeyInfo=orderService2.getAlipayAppKeyInfo();
			AlipayTradeFastpayRefundQueryResponse responese=alipay.alipayTradeFastpayRefundQuery(alipayAppKeyInfo,paySn,customerServiceNumber);
			if(responese.isSuccess()){//请求成功
				return new ResponseEntity<>(new ResponseResultModel<>(new AlipayTradeFastpayRefundQueryResponseVo(responese)), HttpStatus.OK);
			}else{
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		} 
	}
	
	/********************************************
	* 
	* <dl>
	* <dt>支付宝退款接口</dt>
	* </dl>
	* 
	* @return ResponseEntity<?>
	* @author gwq
	* @date 2017年8月19日 13:44:05
	* 
	********************************************/
	@RequestMapping(value = "/aliRefund", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> aliRefund(@RequestBody AlipayRequest alipayRequest,HttpServletRequest request) {
		try {
			logger.info("alipayRequest："+JsonUtil.toJson(alipayRequest));
			//验证售后单号
			if (ParameterUtils.validParams(alipayRequest.getAfterSn())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			// 获取售后信息
			AfterSales afterSale = getOrderService().selectAfterSalesByCustomerServiceNumber(alipayRequest.getAfterSn());
			// 获取父订单的信息
			if(afterSale == null){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20802), HttpStatus.OK);
			}
			/**
			 * 2017-12-17 gwq 直接退款 不管售后单的状态和是否入库
			 */
			if (alipayRequest.getIsGod() == 1) {//一般都是人工干预了退货状态 才会走强制退款
				afterSale.setIsRefund(1);
			}
			if (afterSale.getStatus() == 1) {
				// 请联系工作人员同意退款后再来
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C21205), HttpStatus.OK);
			}
			
			if (afterSale.getStatus() == 3) {
				// 当前订单已经成功售后  请不要重复退钱  不给退的
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C21206), HttpStatus.OK);
			}
			
			if (afterSale.getStatus() == 4) {
				// 被拒绝了  不给退钱
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C21207), HttpStatus.OK);
			}
			
			if (afterSale.getStatus() == 2 && afterSale.getRefundId() != null || "".equals(afterSale.getRefundId())) {
				// 当前状态下  坚决不退钱
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C21210), HttpStatus.OK);
			}
			
			OrderObject orderObject = getOrderService().selectOrderObjectByOrderObjectId(afterSale.getOrderObjectId());
			// 总金额
			long totel = orderObject.getTotalFee().longValue();
			// 现在退款的金额
			long nowMoney = afterSale.getRefundMoney();
			// 已经成功退款的金额
			long successMoney = afterSalesService.getRefundSuccessMoney(orderObject.getId());
			
			// 表示全部退款的金额
			if(totel - successMoney <= 0 || nowMoney == 0){
				afterSale.setRefundId("当前售后订单的实际支付金额为0");
				afterSalesService.userRefundSuccess(afterSale);
//				userEarningsService.CalculateEarningsAfterSale(afterSale.getOrderDetailId(),afterSale.getOrderObjectId());
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			}
			List<OrderPay> PayList=
					orderPayMapper.selectPaySuccessByOrderSn(orderObject.getOrderSn(),orderObject.getPayType());
			if(PayList==null||PayList.size()<=0){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
			}
			OrderSettlementCommision orderSettlementCommision=
					orderSettlementCommisionMapper.selectByorderID(afterSale.getOrderObjectId());
			if(orderSettlementCommision!=null&&orderSettlementCommision.getStatus()!=4){//订单相关未处理
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C21211), HttpStatus.OK);
			}
			OrderPay OrderPay=PayList.get(0);
			AlipayAppKeyInfo alipayAppKeyInfo=getOrderService().getAlipayAppKeyInfo();
			AlipayTradeRefundResponse response = alipay.alipayRefund(alipayAppKeyInfo, OrderPay.getPaySn(),
					orderObject.getPayId(), afterSale.getRefundMoney(), afterSale.getCustomerServiceNumber());
			if (response.isSuccess()) {
				if(response.getFundChange().equals("Y")){
					afterSale.setRefundId("支付宝无退款流水");
					afterSalesService.userRefundSuccess(afterSale);
//					userEarningsService.CalculateEarningsAfterSale(afterSale.getOrderDetailId(),afterSale.getOrderObjectId());
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
				}
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		} catch (AlipayApiException e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		}  catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	private OrderService getOrderService() {
		return orderService2;
	}
}
